<template>
  <div class="container">
    <header>
      <h1>贵州公路建设项目</h1>
      <div class="project-info">S204三都县坝街至扬拱公路改造工程（K18+000-K28+437.466）</div>
      <div class="project-info">施工单位：北京市市政一建设工程有限责任公司 监理单位：贵州省交通建设咨询监理有限公司</div>
    </header>

    <div class="controls">
            <button @click="exportToExcel">导出Excel</button>
            <button @click="openEditModal(0)">编辑数据</button>
            <button @click="addNewProject">添加工程</button>
            <button @click="resetData">重置数据</button>
            <button @click="toggleChartDisplay">
              {{ showChart ? '隐藏工程分配图' : '显示工程分配图' }}
            </button>
            <button @click="toggleBarChartDisplay">
              {{ showBarChart ? '隐藏工期对比图' : '显示工期对比图' }}
            </button>
          </div>

    <div class="gantt-container">
      <table class="gantt-table">
        <thead>
          <tr>
            <th>编号</th>
            <th>工程名称</th>
            <th>计划开始时间</th>
            <th>计划结束时间</th>
            <th>计划工期(d)</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(project, index) in projectData" :key="project.id">
            <td>{{ project.id }}</td>
            <td class="editable" @click="openEditModal(index)">{{ project.name }}</td>
            <td class="editable" @click="openEditModal(index)">{{ project.startDate }}</td>
            <td class="editable" @click="openEditModal(index)">{{ project.endDate }}</td>
            <td class="editable" @click="openEditModal(index)">{{ project.duration }}</td>
            <td>
              <button class="delete-btn" @click.stop="deleteProject(index)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 时间轴容器（包含年份和月份） -->
    <div class="timeline-container">
      <!-- 任务标签头部 -->
      <div class="task-label-header"></div>
      
      <!-- 年份和月份时间轴 -->
      <div class="timeline-content">
        <!-- 2025年部分 -->
        <div class="year-section year-2025">
          <div class="year-title">2025</div>
          <div class="months-container">
            <div class="month">7月</div>
            <div class="month">8月</div>
            <div class="month">9月</div>
            <div class="month">10月</div>
            <div class="month">11月</div>
            <div class="month">12月</div>
          </div>
        </div>
        
        <!-- 2026年部分 -->
        <div class="year-section year-2026">
          <div class="year-title">2026</div>
          <div class="months-container">
            <div class="month">1月</div>
            <div class="month">2月</div>
            <div class="month">3月</div>
            <div class="month">4月</div>
            <div class="month">5月</div>
            <div class="month">6月</div>
            <div class="month">7月</div>
            <div class="month">8月</div>
            <div class="month">9月</div>
            <div class="month">10月</div>
            <div class="month">11月</div>
            <div class="month">12月</div>
          </div>
        </div>
        
        <!-- 2027年部分 -->
        <div class="year-section year-2027">
          <div class="year-title">2027</div>
          <div class="months-container">
            <div class="month">1月</div>
            <div class="month">2月</div>
            <div class="month">3月</div>
            <div class="month">4月</div>
            <div class="month">5月</div>
            <div class="month">6月</div>
          </div>
        </div>
      </div>
    </div>

    <div class="gantt-bars">
      <div v-for="project in projectData" :key="project.id" class="gantt-bar">
        <div class="bar-label">{{ project.name }}</div>
        <div class="bar-container">
            <div 
              :class="['bar', `bar-${project.id}`]" 
              :style="{ left: calculateLeft(project.startDate) + '%', width: calculateWidth(project.startDate, project.endDate) + '%' }"
              :data-project-id="project.id"
            >
            </div>
            <span class="project-percentage" :style="{ left: calculateLeft(project.startDate) + calculateWidth(project.startDate, project.endDate) + 1 + '%' }">
              {{ calculateProjectPercentage(project) }}%
            </span>
          </div>
      </div>
    </div>

    <div class="legend">
      <div v-for="project in projectData" :key="project.id" class="legend-item">
        <div :class="['legend-color', `bar-${project.id}`]"></div>
        <span>{{ project.name }}</span>
      </div>
    </div>
    
    <!-- 工程名称分配图 -->
    <div class="chart-container" v-if="showChart">
      <h3>工程名称分配图</h3>
      <canvas id="project-allocation-chart" class="allocation-chart"></canvas>
    </div>
    
    <!-- 3D项目名称柱状图 -->
    <div class="bar-chart-container" v-if="showBarChart">
      <h3>工程工期对比图</h3>
      <div class="chart-wrapper">
        <canvas id="project-bar-chart" class="bar-chart"></canvas>
      </div>
    </div>

    <!-- 编辑数据模态框 -->
    <div class="modal" v-if="showModal" @click.self="closeEditModal">
      <div class="modal-content">
        <div class="modal-header">
          <div class="modal-title">{{ currentEditIndex !== -1 ? '编辑项目数据' : '添加项目数据' }}</div>
          <div class="close" @click="closeEditModal">&times;</div>
        </div>
        <form @submit.prevent="saveEditData">
          <div class="form-group">
            <label for="projectName">工程名称</label>
            <input type="text" id="projectName" v-model="editingProject.name" required>
          </div>
          <div class="form-group">
            <label for="startDate">计划开始时间</label>
            <input type="date" id="startDate" v-model="editingProject.startDate" required @change="updateDuration">
          </div>
          <div class="form-group">
            <label for="endDate">计划结束时间</label>
            <input type="date" id="endDate" v-model="editingProject.endDate" required @change="updateDuration">
          </div>
          <div class="form-group">
            <label for="duration">计划工期(d) <span class="readonly-hint">(自动计算)</span></label>
            <input type="number" id="duration" v-model="editingProject.duration" min="1" readonly>
          </div>
          <button type="submit">保存</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue';
import * as XLSX from 'xlsx';
import Chart from 'chart.js/auto';

// 项目数据
const initialProjectData = [
  { id: 1, name: "驻地建设", startDate: "2025-07-15", endDate: "2025-08-13", duration: 30 },
  { id: 2, name: "施工便道", startDate: "2025-08-08", endDate: "2025-08-27", duration: 20 },
  { id: 3, name: "预制场", startDate: "2025-10-05", endDate: "2025-11-03", duration: 30 },
  { id: 4, name: "路基土石方工程", startDate: "2025-07-20", endDate: "2026-06-24", duration: 340 },
  { id: 5, name: "防护支挡工程", startDate: "2025-07-25", endDate: "2026-07-09", duration: 350 },
  { id: 6, name: "排水工程", startDate: "2025-07-25", endDate: "2026-07-04", duration: 345 },
  { id: 7, name: "涵洞工程", startDate: "2025-10-15", endDate: "2026-07-11", duration: 270 },
  { id: 8, name: "混凝土路肩加固", startDate: "2025-10-15", endDate: "2026-07-06", duration: 265 },
  { id: 9, name: "级配碎石底基层", startDate: "2026-07-15", endDate: "2026-08-11", duration: 28 },
  { id: 10, name: "水泥稳定碎石基层", startDate: "2026-08-20", endDate: "2026-09-18", duration: 30 },
  { id: 11, name: "沥青面层", startDate: "2026-09-28", endDate: "2026-10-27", duration: 30 },
  { id: 12, name: "交安工程", startDate: "2026-11-05", endDate: "2026-12-04", duration: 30 },
  { id: 13, name: "绿化工程", startDate: "2027-03-05", endDate: "2027-03-24", duration: 20 }
];

const projectData = ref([...initialProjectData]);
const showModal = ref(false);
const currentEditIndex = ref(-1);
const editingProject = reactive({ id: 0, name: '', startDate: '', endDate: '', duration: 0 });
const showChart = ref(true);
const showBarChart = ref(true);
let barChart = null;

// 切换图表显示/隐藏
const toggleChartDisplay = () => {
  showChart.value = !showChart.value;
  if (showChart.value) {
    // 如果从隐藏切换到显示，需要重新绘制图表
    setTimeout(() => {
      drawProjectAllocationChart();
    }, 100);
  }
};

// 切换柱状图显示/隐藏
const toggleBarChartDisplay = () => {
  showBarChart.value = !showBarChart.value;
  if (showBarChart.value) {
    // 如果从隐藏切换到显示，需要重新绘制图表
    setTimeout(() => {
      draw3DProjectBarChart();
    }, 100);
  }
};

// 绘制3D项目名称柱状图
const draw3DProjectBarChart = async () => {
  await nextTick();
  const canvas = document.getElementById('project-bar-chart');
  if (!canvas) return;
  
  // 销毁现有图表
  if (barChart) {
    barChart.destroy();
  }
  
  const ctx = canvas.getContext('2d');
  const width = canvas.offsetWidth;
  const height = canvas.offsetHeight;
  
  // 设置canvas实际大小以避免模糊
  canvas.width = width;
  canvas.height = height;
  
  // 获取项目数据
  const data = projectData.value;
  
  // 为每个项目获取颜色
  const getProjectColor = (projectId) => {
    const ganttBar = document.querySelector(`[data-project-id="${projectId}"]`);
    if (ganttBar) {
      return getComputedStyle(ganttBar).backgroundColor;
    }
    return `var(--bar-${projectId}-color)`;
  };
  
  // 创建3D效果的柱状图
  barChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: data.map(project => {
        // 截断过长的项目名称
        if (project.name.length > 10) {
          return project.name.substring(0, 10) + '...';
        }
        return project.name;
      }),
      datasets: [{
        label: '计划工期(天)',
        data: data.map(project => project.duration),
        backgroundColor: data.map(project => {
          const baseColor = getProjectColor(project.id);
          // 创建渐变以增强3D感
          return baseColor;
        }),
        borderColor: '#ffffff',
        borderWidth: 1,
        borderRadius: {
          topLeft: 6,
          topRight: 6
        },
        barPercentage: 0.6,
        categoryPercentage: 0.7
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: '工程名称工期对比 (3D效果图)',
          font: {
            size: 20,
            weight: 'bold'
          },
          color: '#ffffff',
          padding: 20
        },
        legend: {
          display: false
        },
        tooltip: {
          backgroundColor: 'rgba(0, 0, 0, 0.85)',
          titleColor: '#ffffff',
          bodyColor: '#ffffff',
          borderColor: '#555',
          borderWidth: 1,
          padding: 15,
          displayColors: true,
          callbacks: {
            title: function(context) {
              const index = context[0].dataIndex;
              return data[index].name;
            },
            label: function(context) {
              const index = context.dataIndex;
              const percentage = calculateProjectPercentage(data[index]);
              return [
                `计划工期: ${context.parsed.y} 天`,
                `占比: ${percentage}%`
              ];
            }
          },
          // 添加3D效果的阴影
          shadowColor: 'rgba(0, 0, 0, 0.5)',
          shadowBlur: 10
        }
      },
      scales: {
        x: {
          grid: {
            display: false,
            drawBorder: false
          },
          ticks: {
            color: '#ffffff',
            font: {
              size: 12,
              weight: 'bold'
            },
            maxRotation: 45,
            minRotation: 45
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(255, 255, 255, 0.1)',
            drawBorder: false
          },
          ticks: {
            color: '#ffffff',
            font: {
              size: 12,
              weight: 'bold'
            },
            callback: function(value) {
              return value + ' 天';
            }
          }
        }
      },
      animation: {
        duration: 1500,
        easing: 'easeOutQuart',
        // 自定义动画以增强3D效果
        onComplete: function() {
          // 这里可以添加额外的3D效果绘制
          const chart = this;
          const ctx = chart.ctx;
          const dataset = chart.data.datasets[0];
          const meta = chart.getDatasetMeta(0);
          
          meta.data.forEach((bar, index) => {
            const rect = bar.getBoundingClientRect();
            const chartRect = chart.chartArea;
            
            // 计算柱状图在canvas中的实际位置
            const x = bar.x - bar.width / 2;
            const y = bar.y;
            const barWidth = bar.width;
            const barHeight = chartRect.bottom - bar.y;
            
            // 3D效果参数
            const depth = 15; // 3D深度
            const angle = Math.PI / 6; // 45度角
            const depthX = Math.cos(angle) * depth;
            const depthY = Math.sin(angle) * depth;
            
            // 保存当前状态
            ctx.save();
            
            // 绘制右侧面
            ctx.beginPath();
            ctx.moveTo(x + barWidth, y);
            ctx.lineTo(x + barWidth + depthX, y - depthY);
            ctx.lineTo(x + barWidth + depthX, y + barHeight - depthY);
            ctx.lineTo(x + barWidth, y + barHeight);
            ctx.closePath();
            
            // 右侧面颜色（稍暗）
            const baseColor = getProjectColor(data[index].id);
            ctx.fillStyle = adjustBrightness(baseColor, -20);
            ctx.fill();
            
            // 绘制顶面
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(x + barWidth, y);
            ctx.lineTo(x + barWidth + depthX, y - depthY);
            ctx.lineTo(x + depthX, y - depthY);
            ctx.closePath();
            
            // 顶面颜色（稍亮）
            ctx.fillStyle = adjustBrightness(baseColor, 20);
            ctx.fill();
            
            // 恢复状态
            ctx.restore();
          });
        }
      }
    }
  });
};

// 辅助函数：调整颜色亮度
const adjustBrightness = (color, amount) => {
  // 解析RGB颜色
  let r, g, b;
  if (color.startsWith('rgb')) {
    const matches = color.match(/\d+/g);
    if (matches) {
      r = parseInt(matches[0]);
      g = parseInt(matches[1]);
      b = parseInt(matches[2]);
    }
  } else {
    // 默认颜色
    r = 50;
    g = 150;
    b = 250;
  }
  
  // 调整亮度
  r = Math.max(0, Math.min(255, r + amount));
  g = Math.max(0, Math.min(255, g + amount));
  b = Math.max(0, Math.min(255, b + amount));
  
  return `rgb(${r}, ${g}, ${b})`;
};

// 计算工程工期占比数据
const getProjectAllocationData = () => {
  // 计算总工期天数
  const totalDuration = projectData.value.reduce((sum, project) => sum + project.duration, 0);
  
  // 计算每个工程的工期占比
  return projectData.value.map(project => ({
    name: project.name,
    duration: project.duration,
    percentage: ((project.duration / totalDuration) * 100).toFixed(1),
    id: project.id
  }));
};

// 时间轴范围
const timelineStart = new Date('2025-07-01');
const timelineEnd = new Date('2027-06-30');
const totalDays = Math.ceil((timelineEnd - timelineStart) / (1000 * 60 * 60 * 24)) + 1;

// 计算任务在时间轴上的位置
const calculateLeft = (startDateStr) => {
  const startDate = new Date(startDateStr);
  const daysFromStart = Math.floor((startDate - timelineStart) / (1000 * 60 * 60 * 24));
  return (daysFromStart / totalDays) * 100;
};

// 计算任务在时间轴上的宽度
const calculateWidth = (startDateStr, endDateStr) => {
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);
  const durationDays = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
  return (durationDays / totalDays) * 100;
};

// 根据开始日期和结束日期计算工期天数
const calculateDuration = (startDateStr, endDateStr) => {
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);
  // 计算两个日期之间的天数差并加1（包含起始日期和结束日期）
  return Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
};

// 打开编辑模态框
const openEditModal = (index) => {
  currentEditIndex.value = index;
  if (index >= 0 && index < projectData.value.length) {
    const project = projectData.value[index];
    editingProject.id = project.id;
    editingProject.name = project.name;
    editingProject.startDate = project.startDate;
    editingProject.endDate = project.endDate;
    // 根据开始日期和结束日期自动计算工期天数
    editingProject.duration = calculateDuration(project.startDate, project.endDate);
  }
  showModal.value = true;
};

// 添加新工程
const addNewProject = () => {
  // 创建一个新的工程对象
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);
  
  // 生成新的ID
  const newId = projectData.value.length > 0 
    ? Math.max(...projectData.value.map(p => p.id)) + 1 
    : 1;
  
  // 重置编辑对象
  editingProject.id = newId;
  editingProject.name = '';
  editingProject.startDate = today.toISOString().split('T')[0];
  editingProject.endDate = tomorrow.toISOString().split('T')[0];
  editingProject.duration = 1;
  
  currentEditIndex.value = -1; // -1 表示添加新工程
  showModal.value = true;
};

// 删除工程
const deleteProject = (index) => {
  if (confirm('确定要删除这个工程吗？')) {
    projectData.value.splice(index, 1);
    // 如果图表可见，重新绘制
    if (showChart.value) {
      nextTick(() => {
        drawProjectAllocationChart();
      });
    }
    // 如果柱状图可见，重新绘制
    if (showBarChart.value) {
      nextTick(() => {
        draw3DProjectBarChart();
      });
    }
  }
};

// 关闭编辑模态框
const closeEditModal = () => {
  showModal.value = false;
  currentEditIndex.value = -1;
};

// 当开始日期或结束日期改变时更新工期天数
const updateDuration = () => {
  if (editingProject.startDate && editingProject.endDate) {
    editingProject.duration = calculateDuration(editingProject.startDate, editingProject.endDate);
  }
};

// 保存编辑的数据
const saveEditData = () => {
  if (currentEditIndex.value !== -1 && currentEditIndex.value < projectData.value.length) {
    // 编辑现有工程
    projectData.value[currentEditIndex.value] = { ...editingProject };
  } else {
    // 添加新工程
    projectData.value.push({ ...editingProject });
  }
  
  closeEditModal();
  
  // 如果图表可见，重新绘制
  if (showChart.value) {
    nextTick(() => {
      drawProjectAllocationChart();
    });
  }
  
  // 如果柱状图可见，重新绘制
  if (showBarChart.value) {
    nextTick(() => {
      draw3DProjectBarChart();
    });
  }
};

// 重置数据
const resetData = () => {
  if (confirm('确定要重置所有数据吗？')) {
    projectData.value = [...initialProjectData];
    // 重新绘制所有图表
    nextTick(() => {
      if (showChart.value) {
        drawProjectAllocationChart();
      }
      if (showBarChart.value) {
        draw3DProjectBarChart();
      }
    });
  }
};

// 导出Excel功能，包含完整的表格结构和红框提示
const exportToExcel = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new();
  
  // 创建包含标题和项目信息的工作表数据
  const titleData = [
    ['贵州公路建设项目', '', '', '', ''],
    ['S204三都县城街至扬拱公路改造工程(K18+000-K28+437.466)', '', '', '', ''],
    ['施工工期计划横道图', '', '', '', ''],
    ['', '', '', '', ''],
    ['施工单位：北京市市政一建设工程有限责任公司', '', '', '', ''],
    ['管理单位：贵州省交通建设咨询管理有限公司', '', '', '', ''],
    ['', '', '', '', '']
  ];
  
  // 表头数据 - 添加边框提示
  const headerData = [
    ['编号', '工程名称', '计划开始时间', '计划结束时间', '计划工期(d)'],
    ['(注：请在Excel中为表格区域添加红色边框)', '', '', '', '']
  ];
  
  // 项目数据
  const projectRows = projectData.value.map(project => [
    project.id,
    project.name,
    project.startDate,
    project.endDate,
    project.duration
  ]);
  
  // 底部数据
  const footerData = [
    ['', '', '', '', ''],
    ['编制：', '', '复核：', '', '审核：']
  ];
  
  // 合并所有数据
  const allData = [...titleData, ...headerData, ...projectRows, ...footerData];
  
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(allData);
  
  // 设置列宽
  const wscols = [
    { wch: 8 },  // 编号
    { wch: 25 }, // 工程名称（增加宽度以适应更多内容）
    { wch: 15 }, // 计划开始时间
    { wch: 15 }, // 计划结束时间
    { wch: 12 }  // 计划工期
  ];
  ws['!cols'] = wscols;
  
  // 合并单元格
  ws['!merges'] = [
    // A1:E1 - 项目标题
    { s: { r: 0, c: 0 }, e: { r: 0, c: 4 } },
    // A2:E2 - 项目编号
    { s: { r: 1, c: 0 }, e: { r: 1, c: 4 } },
    // A3:E3 - 图表标题
    { s: { r: 2, c: 0 }, e: { r: 2, c: 4 } },
    // A5:E5 - 施工单位
    { s: { r: 4, c: 0 }, e: { r: 4, c: 4 } },
    // A6:E6 - 管理单位
    { s: { r: 5, c: 0 }, e: { r: 5, c: 4 } },
    // A8:E8 - 边框提示
    { s: { r: 8, c: 0 }, e: { r: 8, c: 4 } }
  ];
  
  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '施工工期计划横道图');
  
  // 生成Excel文件并下载
  const fileName = '贵州公路建设项目进度计划.xlsx';
  XLSX.writeFile(wb, fileName);
  
  // 添加提示信息
  alert('Excel文件导出成功！由于浏览器安全限制，无法直接设置红色边框。\n建议在Excel中：1.选中数据区域 2.使用"开始"选项卡的"边框"工具 3.选择"所有框线"并设置红色。');
  
  console.log('Excel文件导出成功，已包含完整的项目信息和表格结构');
};

// 初始化时确保所有项目的工期天数正确
const validateProjectDurations = () => {
  projectData.value = projectData.value.map(project => ({
    ...project,
    duration: calculateDuration(project.startDate, project.endDate)
  }));
};

// 绘制工程名称分配图（环形图）
const drawProjectAllocationChart = async () => {
  await nextTick();
  const canvas = document.getElementById('project-allocation-chart');
  if (!canvas) return;
  
  const ctx = canvas.getContext('2d');
  const width = canvas.offsetWidth;
  const height = canvas.offsetHeight;
  
  // 设置canvas实际大小以避免模糊
  canvas.width = width;
  canvas.height = height;
  
  // 清空画布
  ctx.clearRect(0, 0, width, height);
  
  const data = getProjectAllocationData();
  if (data.length === 0) return;
  
  // 重新计算图表尺寸，增大环形图占比
  const centerX = width * 0.35; // 调整位置使图表更大
  const centerY = height / 2;
  const radius = Math.min(width * 0.3, height * 0.4); // 增大半径
  const innerRadius = radius * 0.6; // 调整内环比例
  
  // 绘制环形图
  let currentAngle = -Math.PI / 2; // 从顶部开始
  
  data.forEach(project => {
    // 计算扇形角度
    const sliceAngle = (parseFloat(project.percentage) / 100) * 2 * Math.PI;
    
    // 绘制扇形
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
    ctx.arc(centerX, centerY, innerRadius, currentAngle + sliceAngle, currentAngle, true);
    ctx.closePath();
    
    // 从甘特图样式中获取颜色
    const ganttBar = document.querySelector(`[data-project-id="${project.id}"]`);
    let barColor = `var(--bar-${project.id}-color)`;
    if (ganttBar) {
      barColor = getComputedStyle(ganttBar).backgroundColor;
    }
    
    // 设置更鲜艳的颜色
    ctx.fillStyle = barColor;
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 3; // 加粗边框更清晰
    ctx.fill();
    ctx.stroke();
    
    // 计算并绘制标签位置
    const labelAngle = currentAngle + sliceAngle / 2;
    const labelRadius = innerRadius + (radius - innerRadius) / 2;
    const labelX = centerX + Math.cos(labelAngle) * labelRadius;
    const labelY = centerY + Math.sin(labelAngle) * labelRadius;
    
    // 所有扇形都显示百分比，调整字体大小
    ctx.fillStyle = isColorDark(barColor) ? '#fff' : '#333';
    ctx.font = 'bold 14px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(`${project.percentage}%`, labelX, labelY);
    
    // 更新当前角度
    currentAngle += sliceAngle;
  });
  
  // 绘制图例
  const legendX = width * 0.65;
  const legendY = height * 0.2;
  const legendItemHeight = 28;
  const legendItemWidth = width * 0.3;
  
  data.forEach((project, index) => {
    const itemY = legendY + index * legendItemHeight;
    
    // 从甘特图样式中获取颜色
    const ganttBar = document.querySelector(`[data-project-id="${project.id}"]`);
    let barColor = `var(--bar-${project.id}-color)`;
    if (ganttBar) {
      barColor = getComputedStyle(ganttBar).backgroundColor;
    }
    
    // 绘制颜色块
    ctx.fillStyle = barColor;
    ctx.fillRect(legendX, itemY, 24, 18);
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 1;
    ctx.strokeRect(legendX, itemY, 24, 18);
    
    // 绘制工程名称和数据
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'top';
    
    // 确保文本不超出画布
    let displayName = project.name;
    const maxTextWidth = legendItemWidth - 30;
    if (ctx.measureText(displayName).width > maxTextWidth) {
      // 截断过长的工程名称
      while (displayName.length > 0 && ctx.measureText(displayName + '...').width > maxTextWidth) {
        displayName = displayName.substring(0, displayName.length - 1);
      }
      displayName += '...';
    }
    
    // 分两行显示：工程名称和天数在第一行，百分比在第二行
    ctx.fillText(`${displayName}`, legendX + 30, itemY);
    ctx.fillText(`(${project.duration}天)`, legendX + 30 + ctx.measureText(displayName + ' ').width, itemY);
    
    // 百分比显示在第二行，更清晰
    ctx.fillStyle = barColor;
    ctx.font = 'bold 14px Arial';
    ctx.fillText(`${project.percentage}%`, legendX + 30, itemY + 18);
  });
  
  // 绘制图表标题
  ctx.fillStyle = '#333';
  ctx.font = '18px Arial';
  ctx.textAlign = 'center';
  ctx.fillText('工程工期分配比例', width / 2, 35);
};

// 判断颜色是否为深色，用于决定文字颜色
const isColorDark = (color) => {
  // 简单实现：解析颜色值并计算亮度
  let r, g, b;
  if (color.startsWith('rgb')) {
    const matches = color.match(/\d+/g);
    if (matches) {
      r = parseInt(matches[0]);
      g = parseInt(matches[1]);
      b = parseInt(matches[2]);
    }
  } else {
    // 如果是十六进制颜色或其他格式，返回默认值
    return false;
  }
  
  // 计算亮度 (0-255)
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness < 128; // 亮度低于128视为深色
};

// 计算项目占总工期的百分比
const calculateProjectPercentage = (project) => {
  const totalDuration = projectData.value.reduce((sum, p) => sum + p.duration, 0);
  if (totalDuration === 0) return '0.0';
  return ((project.duration / totalDuration) * 100).toFixed(1);
};

// 监听窗口大小变化，重新绘制图表
const handleResize = () => {
  if (showChart.value) {
    drawProjectAllocationChart();
  }
  if (showBarChart.value) {
    draw3DProjectBarChart();
  }
};

// 监听数据变化，重新绘制图表
watch(() => projectData.value, () => {
  // 当项目数据变化时重新计算并绘制分配图
  if (showChart.value) {
    drawProjectAllocationChart();
  }
}, { deep: true });

onMounted(() => {
  console.log('GanttChart 组件已挂载');
  // 组件挂载后验证并修正所有项目的工期天数
  validateProjectDurations();
  // 绘制工程名称分配图
  drawProjectAllocationChart();
  // 绘制3D项目名称柱状图
  draw3DProjectBarChart();
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 组件挂载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

header {
  text-align: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #2c80c5;
  padding-bottom: 15px;
}

h1 {
  color: #2c80c5;
  font-size: 24px;
  margin-bottom: 10px;
}

.project-info {
  font-size: 16px;
  color: #666;
  margin-bottom: 5px;
}

.controls {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.gantt-table td:last-child {
  width: 80px;
  text-align: center;
}

button {
  padding: 8px 16px;
  background-color: #2c80c5;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #1e5f9e;
}

.gantt-container {
  overflow-x: auto;
  margin-top: 20px;
}

.gantt-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

.gantt-table th,
.gantt-table td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: center;
}

.gantt-table th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.gantt-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.gantt-table tr:hover {
  background-color: #f1f7fd;
}

.editable {
  cursor: pointer;
  position: relative;
}

.editable:hover {
  background-color: #e6f3ff;
}

/* 时间轴容器 */
.timeline-container {
  margin-top: 30px;
  display: flex;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

/* 任务标签头部空白单元格 */
.task-label-header {
  width: 160px;
  border-right: 1px solid #ddd;
  background-color: #e9ecef;
}

/* 时间轴内容区域 */
.timeline-content {
  display: flex;
  flex: 1;
}

/* 年份区段 */
.year-section {
  display: flex;
  flex-direction: column;
}

/* 年份区段宽度设置 */
.year-2025 {
  width: calc(6/24 * 100%); /* 6个月占比 */
}

.year-2026 {
  width: calc(12/24 * 100%); /* 12个月占比 */
}

.year-2027 {
  width: calc(6/24 * 100%); /* 6个月占比 */
}

/* 年份标题 */
.year-title {
  text-align: center;
  font-weight: bold;
  padding: 8px;
  border-bottom: 1px solid #ddd;
  font-size: 14px;
}

/* 年份特殊颜色 */
.year-2025 .year-title {
  background-color: #e1f5fe;
}

.year-2026 .year-title {
  background-color: #e8f5e9;
}

.year-2027 .year-title {
  background-color: #fff3e0;
}

/* 月份容器 */
.months-container {
  display: flex;
  height: 40px;
}

/* 月份样式 */
.month {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  border-right: 1px solid #ddd;
  height: 100%;
  background-color: #f8f9fa;
}

/* 确保年份区段之间的边框正确显示 */
.year-section:not(:last-child) {
  border-right: 2px solid #ddd;
}

.month:last-child {
  border-right: none;
}

.gantt-bars {
  margin-top: 0;
}

.gantt-bar {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.bar-label {
  width: 150px;
  padding-right: 10px;
  text-align: right;
  font-size: 14px;
  border-right: 1px solid #ddd;
}

.bar-container {
  flex: 1;
  height: 10px;
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-left: none;
  position: relative;
  overflow: hidden;
}

.bar {
  height: calc(70% + 2px);
  top: calc(15% - 1px);
  background-color: #2c80c5;
  border-radius: 4px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8px;
  font-size: 11px;
  overflow: hidden;
  color: white;
}

.project-percentage {
  font-weight: bold;
  white-space: nowrap;
  background-color: rgba(0, 0, 0, 0.2);
  padding: 2px 6px;
  border-radius: 3px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 11px;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .project-percentage {
    font-size: 10px;
    padding: 2px 4px;
  }
}

.bar-1 { background-color: #2196F3; }
.bar-2 { background-color: #FF9800; }
.bar-3 { background-color: #9C27B0; }
.bar-4 { background-color: #F44336; }
.bar-5 { background-color: #607D8B; }
.bar-6 { background-color: #795548; }
.bar-7 { background-color: #009688; }
.bar-8 { background-color: #CDDC39; }
.bar-9 { background-color: #FF5722; }
.bar-10 { background-color: #673AB7; }
.bar-11 { background-color: #00BCD4; }
.bar-12 { background-color: #8BC34A; }
.bar-13 { background-color: #E91E63; }

.legend {
  display: flex;
  flex-wrap: wrap;
  margin-top: 30px;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 5px 15px;
}

.legend-color {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  border-radius: 4px;
}

/* 工程名称分配图样式 */
  .chart-container {
    margin-top: 40px;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    background-color: #fafafa;
  }

  .chart-container h3 {
    margin-top: 0;
    margin-bottom: 20px;
    color: #333;
    font-size: 18px;
    text-align: center;
  }

  .allocation-chart {
    width: 100%;
    height: 400px;
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
  
  .bar-chart-container {
    margin-top: 40px;
    padding: 20px;
    background-color: #0a1929; /* 深蓝色背景 */
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
  
  .bar-chart-container h3 {
    color: #ffffff;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .chart-wrapper {
    position: relative;
    height: 500px;
    width: 100%;
  }
  
  .bar-chart {
    width: 100% !important;
    height: 100% !important;
  }

  .bar-chart-container {
    margin-top: 40px;
    padding: 20px;
    background-color: #0a1929; /* 深蓝色背景 */
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .bar-chart-container h3 {
    color: #ffffff;
    text-align: center;
    margin-bottom: 20px;
  }

  .chart-wrapper {
    position: relative;
    height: 500px;
    width: 100%;
  }

  .bar-chart {
    width: 100% !important;
    height: 100% !important;
  }

/* 定义颜色变量以便在环形图中使用 */
:root {
  --bar-1-color: #2196F3;
  --bar-2-color: #FF9800;
  --bar-3-color: #9C27B0;
  --bar-4-color: #F44336;
  --bar-5-color: #607D8B;
  --bar-6-color: #795548;
  --bar-7-color: #009688;
  --bar-8-color: #CDDC39;
  --bar-9-color: #FF5722;
  --bar-10-color: #673AB7;
  --bar-11-color: #00BCD4;
  --bar-12-color: #8BC34A;
  --bar-13-color: #E91E63;
}

@media (max-width: 768px) {
  .allocation-chart {
    height: 450px; /* 移动端增加高度以容纳图例 */
  }
  
  .chart-container {
    padding: 15px;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.close {
  font-size: 24px;
  cursor: pointer;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .readonly-hint {
    font-size: 12px;
    color: #666;
    font-weight: normal;
  }
  
  .form-group input[readonly] {
    background-color: #f8f9fa;
    cursor: not-allowed;
  }

@media (max-width: 768px) {
  .container {
    padding: 10px;
  }

  .bar-label {
    width: 120px;
    font-size: 12px;
  }

  .task-label-header {
    width: 120px;
  }

  .month {
    font-size: 10px;
  }

  .year-title {
    font-size: 12px;
    padding: 6px;
  }

  .months-container {
    height: 35px;
  }

  .controls {
    flex-direction: column;
  }
}
</style>